'use client';

import React, { createContext, useContext, useReducer, ReactNode } from 'react';
import { CartItem, User, Product, SignInRecord, LotteryResult, PurchasedBox } from '@/lib/types';
import { mockUser, products, mockSignInRecord, lotteryPrizes } from '@/lib/mockData';

// 状态类型
interface AppState {
  user: User | null;
  cart: CartItem[];
  isLoggedIn: boolean;
  cartTotal: number;
  cartCount: number;
  signInRecord: SignInRecord | null;
  lotteryChances: number;
  todaySignedIn: boolean;
  lotteryResults: LotteryResult[];
  purchasedBoxes: PurchasedBox[];
}

// 动作类型
type AppAction =
  | { type: 'LOGIN'; payload: User }
  | { type: 'LOGOUT' }
  | { type: 'ADD_TO_CART'; payload: Product }
  | { type: 'REMOVE_FROM_CART'; payload: string }
  | { type: 'UPDATE_CART_QUANTITY'; payload: { productId: string; quantity: number } }
  | { type: 'CLEAR_CART' }
  | { type: 'SIGN_IN'; payload: { reward: string; lotteryChances: number } }
  | { type: 'USE_LOTTERY_CHANCE' }
  | { type: 'ADD_LOTTERY_RESULT'; payload: LotteryResult }
  | { type: 'LOAD_SIGN_IN_DATA'; payload: { signInRecord: SignInRecord; lotteryChances: number; todaySignedIn: boolean; lotteryResults: LotteryResult[] } }
  | { type: 'PURCHASE_BOX'; payload: PurchasedBox }
  | { type: 'UNBOX_ITEM'; payload: { boxId: string; unboxResult: any } };

// 从localStorage获取初始购物车状态
const getInitialCartState = () => {
  if (typeof window !== 'undefined') {
    try {
      const savedCart = localStorage.getItem('xiangye_cart');
      if (savedCart) {
        const cart = JSON.parse(savedCart);
        const cartTotal = cart.reduce((total: number, item: CartItem) => total + (item.product.price * item.quantity), 0);
        const cartCount = cart.reduce((count: number, item: CartItem) => count + item.quantity, 0);
        return { cart, cartTotal, cartCount };
      }
    } catch (error) {
      console.error('Error loading cart from localStorage:', error);
    }
  }
  return { cart: [], cartTotal: 0, cartCount: 0 };
};

// 从localStorage获取签到状态
const getInitialSignInState = () => {
  if (typeof window !== 'undefined') {
    try {
      const savedSignIn = localStorage.getItem('xiangye_signin');
      const savedLotteryChances = localStorage.getItem('xiangye_lottery_chances');
      const savedLotteryResults = localStorage.getItem('xiangye_lottery_results');
      const today = new Date().toISOString().split('T')[0];
      
      if (savedSignIn) {
        const signInRecord = JSON.parse(savedSignIn);
        const lotteryChances = savedLotteryChances ? parseInt(savedLotteryChances) : 0;
        const lotteryResults = savedLotteryResults ? JSON.parse(savedLotteryResults) : [];
        const todaySignedIn = signInRecord.lastSignInDate === today;
        return { signInRecord, lotteryChances, todaySignedIn, lotteryResults };
      }
    } catch (error) {
      console.error('Error loading sign-in data from localStorage:', error);
    }
  }
  return { 
    signInRecord: mockSignInRecord, 
    lotteryChances: 2, 
    todaySignedIn: false,
    lotteryResults: []
  };
};

// 从 localStorage 获取购买的盲盒
const getInitialPurchasedBoxes = (): PurchasedBox[] => {
  if (typeof window !== 'undefined') {
    try {
      const saved = localStorage.getItem('xiangye_purchased_boxes');
      return saved ? JSON.parse(saved) : [];
    } catch (error) {
      console.error('Error loading purchased boxes:', error);
    }
  }
  return [];
};

// 初始状态
const initialCartState = getInitialCartState();
const initialSignInState = getInitialSignInState();
const initialPurchasedBoxes = getInitialPurchasedBoxes();
const initialState: AppState = {
  user: null,
  cart: initialCartState.cart,
  isLoggedIn: false,
  cartTotal: initialCartState.cartTotal,
  cartCount: initialCartState.cartCount,
  signInRecord: initialSignInState.signInRecord,
  lotteryChances: initialSignInState.lotteryChances,
  todaySignedIn: initialSignInState.todaySignedIn,
  lotteryResults: initialSignInState.lotteryResults,
  purchasedBoxes: initialPurchasedBoxes
};

// 状态reducer
const appReducer = (state: AppState, action: AppAction): AppState => {
  switch (action.type) {
    case 'LOGIN':
      return {
        ...state,
        user: action.payload,
        isLoggedIn: true
      };
    
    case 'LOGOUT':
      return {
        ...state,
        user: null,
        isLoggedIn: false,
        cart: []
      };
    
    case 'ADD_TO_CART': {
      const existingItem = state.cart.find(item => item.product.id === action.payload.id);
      let newCart: CartItem[];
      
      if (existingItem) {
        newCart = state.cart.map(item =>
          item.product.id === action.payload.id
            ? { ...item, quantity: item.quantity + 1 }
            : item
        );
      } else {
        newCart = [...state.cart, { product: action.payload, quantity: 1 }];
      }
      
      const cartTotal = newCart.reduce((total, item) => total + (item.product.price * item.quantity), 0);
      const cartCount = newCart.reduce((count, item) => count + item.quantity, 0);
      
      // 保存到localStorage
      if (typeof window !== 'undefined') {
        localStorage.setItem('xiangye_cart', JSON.stringify(newCart));
      }
      
      return {
        ...state,
        cart: newCart,
        cartTotal,
        cartCount
      };
    }
    
    case 'REMOVE_FROM_CART': {
      const newCart = state.cart.filter(item => item.product.id !== action.payload);
      const cartTotal = newCart.reduce((total, item) => total + (item.product.price * item.quantity), 0);
      const cartCount = newCart.reduce((count, item) => count + item.quantity, 0);
      
      // 保存到localStorage
      if (typeof window !== 'undefined') {
        localStorage.setItem('xiangye_cart', JSON.stringify(newCart));
      }
      
      return {
        ...state,
        cart: newCart,
        cartTotal,
        cartCount
      };
    }
    
    case 'UPDATE_CART_QUANTITY': {
      const newCart = state.cart.map(item =>
        item.product.id === action.payload.productId
          ? { ...item, quantity: action.payload.quantity }
          : item
      ).filter(item => item.quantity > 0);
      
      const cartTotal = newCart.reduce((total, item) => total + (item.product.price * item.quantity), 0);
      const cartCount = newCart.reduce((count, item) => count + item.quantity, 0);
      
      // 保存到localStorage
      if (typeof window !== 'undefined') {
        localStorage.setItem('xiangye_cart', JSON.stringify(newCart));
      }
      
      return {
        ...state,
        cart: newCart,
        cartTotal,
        cartCount
      };
    }
    
    case 'CLEAR_CART':
      // 清空localStorage
      if (typeof window !== 'undefined') {
        localStorage.removeItem('xiangye_cart');
      }
      return {
        ...state,
        cart: [],
        cartTotal: 0,
        cartCount: 0
      };
    
    case 'SIGN_IN': {
      const today = new Date().toISOString().split('T')[0];
      const newSignInRecord: SignInRecord = {
        ...state.signInRecord!,
        lastSignInDate: today,
        consecutiveDays: state.signInRecord!.lastSignInDate === new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString().split('T')[0] 
          ? state.signInRecord!.consecutiveDays + 1 
          : 1,
        totalDays: state.signInRecord!.totalDays + 1
      };
      
      const newLotteryChances = state.lotteryChances + action.payload.lotteryChances;
      
      // 保存到localStorage
      if (typeof window !== 'undefined') {
        localStorage.setItem('xiangye_signin', JSON.stringify(newSignInRecord));
        localStorage.setItem('xiangye_lottery_chances', newLotteryChances.toString());
      }
      
      return {
        ...state,
        signInRecord: newSignInRecord,
        lotteryChances: newLotteryChances,
        todaySignedIn: true
      };
    }
    
    case 'USE_LOTTERY_CHANCE': {
      const newLotteryChances = Math.max(0, state.lotteryChances - 1);
      
      // 保存到localStorage
      if (typeof window !== 'undefined') {
        localStorage.setItem('xiangye_lottery_chances', newLotteryChances.toString());
      }
      
      return {
        ...state,
        lotteryChances: newLotteryChances
      };
    }
    
    case 'ADD_LOTTERY_RESULT': {
      const newLotteryResults = [action.payload, ...state.lotteryResults];
      
      // 保存到localStorage
      if (typeof window !== 'undefined') {
        localStorage.setItem('xiangye_lottery_results', JSON.stringify(newLotteryResults));
      }
      
      return {
        ...state,
        lotteryResults: newLotteryResults
      };
    }
    
    case 'LOAD_SIGN_IN_DATA':
      return {
        ...state,
        signInRecord: action.payload.signInRecord,
        lotteryChances: action.payload.lotteryChances,
        todaySignedIn: action.payload.todaySignedIn,
        lotteryResults: action.payload.lotteryResults
      };
    
    case 'PURCHASE_BOX': {
      const newPurchasedBoxes = [action.payload, ...state.purchasedBoxes];
      
      // 保存到 localStorage
      if (typeof window !== 'undefined') {
        localStorage.setItem('xiangye_purchased_boxes', JSON.stringify(newPurchasedBoxes));
      }
      
      return {
        ...state,
        purchasedBoxes: newPurchasedBoxes
      };
    }
    
    case 'UNBOX_ITEM': {
      const updatedBoxes = state.purchasedBoxes.map(box => 
        box.id === action.payload.boxId 
          ? { ...box, isUnboxed: true, unboxResult: action.payload.unboxResult }
          : box
      );
      
      // 保存到 localStorage
      if (typeof window !== 'undefined') {
        localStorage.setItem('xiangye_purchased_boxes', JSON.stringify(updatedBoxes));
      }
      
      return {
        ...state,
        purchasedBoxes: updatedBoxes
      };
    }
    
    default:
      return state;
  }
};

// Context创建
const AppContext = createContext<{
  state: AppState;
  dispatch: React.Dispatch<AppAction>;
} | null>(null);

// Provider组件
export const AppProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [state, dispatch] = useReducer(appReducer, initialState);

  return (
    <AppContext.Provider value={{ state, dispatch }}>
      {children}
    </AppContext.Provider>
  );
};

// Hook
export const useApp = () => {
  const context = useContext(AppContext);
  if (!context) {
    throw new Error('useApp must be used within AppProvider');
  }
  return context;
};

// 初始化用户登录的Hook
export const useInitializeUser = () => {
  const { dispatch } = useApp();
  
  React.useEffect(() => {
    // 模拟自动登录
    dispatch({ type: 'LOGIN', payload: mockUser });
  }, [dispatch]);
};